package cn.com.pagoda.ideplugin.service;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: lyq
 * @Date: 2023/6/18 3:24 PM
 */
public class ExcelConversionService {

    /**
     * Excel文件转成json对象
     * @param file excel文件
     * @return
     * @throws IOException
     */
    public static JSONObject convert(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        Row firstRow = sheet.getRow(0);
        JSONArray dataRows = new JSONArray();
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            Row row = sheet.getRow(i);
            JSONObject rowData = new JSONObject();
            for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                Cell cell = row.getCell(j);
                String columnName = firstRow.getCell(j).getStringCellValue();
                rowData.put(columnName, cell.getStringCellValue());
            }
            dataRows.put(rowData);
        }
        workbook.close();
        inputStream.close();
        JSONObject result = new JSONObject();
        result.put("data", dataRows);
        return result;
    }

    /**
     * 多行数据转json对象
     * <p>
     *     1、text存在空格，会转换成"\t"
     *     2、text存在多个"\t"，只保留一个
     * </p>
     *
     * @param text 多行数据转json对象
     * @return
     */
    public static JSONObject textConvert(String text) {
        String replaceText = text.replace(" ", "\t");
        replaceText = removeAllAdjacentDuplicates(replaceText, "\t");
        String[] lines = replaceText.split("\n");
        String[] columnNames = lines[0].split("\t");

        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 1; i < lines.length; i++) {
            String[] values = lines[i].split("\t");
            LinkedHashMap<String, Object> rowData = new LinkedHashMap<>();
            for (int j = 0; j < columnNames.length; j++) {
                rowData.put(columnNames[j], values[j]);
            }
            dataList.add(rowData);
        }
        JSONObject result = new JSONObject();
        result.put("data", dataList);
        return result;
    }

    /**
     * 去除指定字符串的相邻重复项，只保留一个
     *
     * <p>
     *     例如：    "field1\t\t\tfield2\t\tfield3\tfield4\tfield5\tfield6"
     *     返回结果："field1\tfield2\tfield3\tfield4\tfield5\tfield6"
     * </p>
     * @param str 字符串
     * @param target 指定去除重复字符串
     * @return
     */
    private static String removeAllAdjacentDuplicates(String str, String target) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return str.replaceAll("("+ target +")+", "$1");
    }
}
